<?php

class FileController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	//public $layout='//layouts/column2';
	//public $menu_title='新闻类别';
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','download'),
				'users'=>array('*'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
	    $model=File::model()->findByPk($id);
	    if($model===null)
	        throw new CHttpException(404,'The requested page does not exist.');
	    
	    $file_type_model = FileType::model();
	    $file_type_list = $file_type_model -> findAll();
	    
		$this->render('view',array(
			'model'=>$model,
		    'file_type_list'=>$file_type_list,
		));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
	    
	    $file_type_model = FileType::model();
	    $file_type_list = $file_type_model -> findAll();
	    
	    $show_title ='';
	    if(isset($_GET['file_type'])&&!empty($_GET['file_type'])){
	    	$condition = "file_type='".$_GET['file_type']."'";
	    	$show_title = $file_type_model -> getTypeName($_GET['file_type']);
	    }else{
	        $condition = '';
	    }
	    
		$dataProvider=new CActiveDataProvider('File',array(
	        'criteria'=>array(
                'select'=>'*',
                'order'=>'file_addtime desc',
		        'condition' => $condition,
	        ),
		));
		
		$this->render('index',array(
            'file_type_list'=>$file_type_list,
			'dataProvider'=>$dataProvider,
		    'show_title'=>$show_title,
		));
	}
	

	public function actionDownload(){
	
	    if (isset($_GET["file_id"])) {
	        $file_id = $_GET["file_id"];
	        $model = File::model()->find('file_id =:file_id', array('file_id' => $file_id));
	        
	        if ($model == null) {
	            throw new CHttpException ('500', '文件不存在');
	        } else {
	            $model->download_times +=1;
	            $model->save();
	            // 服务器端文件的路径
	            $fileName = './assets/upload/file/'.$model->file_path;
	            $pathinfo = pathinfo($fileName);
	            if (file_exists($fileName)){
	                yii::app ()->request->sendFile ($model->file_name.".".$pathinfo['extension'],  file_get_contents ($fileName));
	            }
	        }
	    }
	}
	

}
